"""Redis配置"""
import redis
from typing import Optional
from .config import get_settings

settings = get_settings()

# 创建Redis客户端
try:
    # 尝试连接Redis，不强制要求连接成功
    redis_client = redis.from_url(
        settings.redis_url,
        encoding="utf-8",
        decode_responses=True,
        socket_connect_timeout=5,
        socket_timeout=5
    )
    # 静默测试连接，失败也不中断服务
    try:
        redis_client.ping()
        print("Redis连接成功")
    except Exception as e:
        print(f"Redis连接测试失败: {e}")
        # 不设置为None，保持客户端对象用于后续操作尝试
except Exception as e:
    print(f"Redis客户端初始化失败: {e}")
    redis_client = None


def get_redis() -> Optional[redis.Redis]:
    """获取Redis客户端"""
    if redis_client is None:
        print("警告: Redis客户端未初始化，返回None")
        return None
    return redis_client
